package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.concurrent.*;

import static cn.itcast.n2.util.Sleeper.sleep;

@Slf4j(topic = "c.TestCyclicBarrier")
public class TestCyclicBarrier {
    public static void main(String[] args) {
        final ExecutorService service = Executors.newFixedThreadPool(2);
//        final CountDownLatch latch = new CountDownLatch(2);
        final CyclicBarrier barrier = new CyclicBarrier(2,()->{
            log.debug("task1 task2 finish...");
        });

        for (int i = 0; i < 3; i++) {
            service.submit(()->{
                log.debug("task1 start...");
                sleep(1);
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                log.debug("task1 running...");
            });

            service.submit(()->{
                log.debug("task1 start...");
                sleep(2);
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                log.debug("task1 running...");
            });
        }

//        System.out.println(LocalDateTime.now());

        service.shutdown();
    }
}
